package com.surfacing.rcp.server.run;

import java.util.MissingResourceException;
import java.util.ResourceBundle;

import org.apache.log4j.Logger;
import org.apache.log4j.PropertyConfigurator;

import com.surfacing.rcp.core.net.internal.MyServer;
import com.surfacing.rcp.db.DataSource;
import com.surfacing.rcp.server.controller.ClientHandler;
import com.surfacing.rcp.server.controller.ServerController;

/**
 * Tacos server
 * 
 * @author Michael
 */
public class NefJournalServer {
	// path for the properties file
	public final static String SERVER_CONFIG = "com.surfacing.rcp.server.config.server";
	// the logging instance
	private static Logger logger = Logger.getLogger(NefJournalServer.class);

	// the server object
	private MyServer myServer = null;

	public NefJournalServer(int port) {
		ServerController.getDefault();
		// listen for client request
		myServer = new MyServer(port);
		myServer.addNetListener(new ClientHandler());
	}

	/**
	 * Starts the server thread to listen for client requests.
	 */
	private void startServer() {
		// start the server thread to listen to client connections
		Thread t = new Thread(myServer);
		t.start();
	}

	/**
	 * The main method to read the configuration and start the server
	 * 
	 * @param args
	 *            - not used
	 */
	public static void main(String[] args) {
		try {
			PropertyConfigurator.configureAndWatch("log4j.properties",
					60 * 1000);
			// load the settings from the file
			String strPort = ResourceBundle.getBundle(SERVER_CONFIG).getString(
					"server.port");
			int port = -1;
			// parse
			port = Integer.parseInt(strPort);
			// start the server
			logger.info("Open a connection to the database server");
			// try to get a connection to the database
			if (DataSource.getInstance().getConnection() == null) {
				logger.error("Failed to connect to the database");
				logger.error("Shuting down the server");
				System.exit(1);
			}
			logger.info("Listening for client request at port: " + port);
			NefJournalServer server = new NefJournalServer(port);
			server.startServer();

		} catch (MissingResourceException mre) {
			logger.error("Missing resource, cannot init startup server");
			logger.error(mre.getMessage());
		} catch (NumberFormatException nfe) {
			logger.info("Port number must be a integer");
			logger.info(nfe.getMessage());
		} catch (NullPointerException npe) {
			logger.info("Configuration file for the server is missing");
			logger.info(npe.getMessage());
			npe.printStackTrace();
		}
	}
}
